<?php
/**
 * Created by jinqiang on 2024/9/12 17:32.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Soa;


use AlibabaCloud\Tea\Request;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsyPurchaseReturnTable;
use App\Http\Models\Mysql\SsyRepairAmountTable;
use App\Http\Models\Mysql\SsyRepairReconciliationOrderTable;

class RepairService
{
    public function search($param)
    {
        $conn = new SsyRepairAmountTable();
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('processing_code', $param['processing_code']);
        }
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', 'like', $param['type_no']."%");
        }
        if(isset($param['groups']) && $param['groups'] != ""){
            $conn = $conn->where('groups', (Int)$param['groups']);
        }
        if($param['jy_withdrawal_number'] ?? ""){
            $conn = $conn->where('jy_withdrawal_number', 'like', $param['jy_withdrawal_number']."%");
        }
        if(isset($param['k_status']) && $param['k_status'] != ""){
            $conn = $conn->where('k_status', (Int)$param['k_status']);
        }
        if($param['supplier_id'] ?? ""){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        if($param['recon_time'] ?? ""){
            $start = $param['recon_time']."-01 00:00:00";
            $end = date('Y-m-t 23:59:59', strtotime($start));
            $conn = $conn->whereBetween("createtime", [$start, $end]);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function searchM($param)
    {
        $conn = new SsyRepairReconciliationOrderTable();
        if($param['supplier_id'] ?? ""){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        if($param['recon_time'] ?? ""){
            $conn = $conn->where('recon_time', $param['recon_time']);
        }
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if(isset($param['pay_status']) && $param['pay_status'] != ""){
            $conn = $conn->where('pay_status', (Int)$param['pay_status']);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $subjects = array_column(config("scm.subject"), 'brand_name', 'supplier_id');
        foreach ($res['data'] as &$item){
            $item['pay_images'] = !empty($item['pay_images']) ? unserialize($item['pay_images']) : "";
            $item['brand_name'] = $subjects[$item['source_factory_groups_id']] ?? "";
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function cancel($id)
    {
        $repairReconciliationObj = (new SsyRepairReconciliationOrderTable())->where('id', $id)->first()->toArray();
        //回货单更新:未抵扣
        if(!empty($repairReconciliationObj['purchasein_ids'])){
            $ids = unserialize($repairReconciliationObj['purchasein_ids']);
            (new SsyJstPurchaseinOrderEmbroideryCountTable())->updateData($ids, ['k_status' => 0, 'r_id' => 0]);
        }
        //返修单
        if(!empty($repairReconciliationObj['repair_ids'])){
            $ids = unserialize($repairReconciliationObj['repair_ids']);
            (new SsyRepairAmountTable())->updateData($ids, ['k_status' => 0, 'r_id' => 0]);
        }
        return (new SsyRepairReconciliationOrderTable())->updateData($id, ['status' => 3]);
    }

    public function check($id, $status)
    {
        $repairReconciliationObj = (new SsyRepairReconciliationOrderTable())->where('id', $id)->first()->toArray();
        //审核通过
        if($status == 1){
            //返修更新: 抵扣
            if(!empty($repairReconciliationObj['repair_ids'])){
                $ids = unserialize($repairReconciliationObj['repair_ids']);
                (new SsyRepairAmountTable())->updateDataWhere(['id' => ['in' => $ids]], ['k_status' => 2, 'r_id' => $id]);
            }
            //回货单记录更新: 已抵扣
            if(!empty($repairReconciliationObj['purchasein_ids'])){
                $purchaseinIds = unserialize($repairReconciliationObj['purchasein_ids']);
                $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $purchaseinIds)->get(['ids'])->toArray();
                foreach ($returnList as $item){
                    if(!empty($item['ids'])) {
                        (new SsyJstPurchaseinOrderTable())->updateData(unserialize($item['ids']), ['k_status' => 1]);
                    }
                }
            }
        }
        return (new SsyRepairReconciliationOrderTable())->updateData($id, [
            'status' => $status, 'to_examine_time' => date("Y-m-d H:i:s"), 'to_examine_user' => auth()->guard("api")->user()->name
        ]);
    }

    public function pay($id, $images)
    {
        return (new SsyRepairReconciliationOrderTable())->updateData($id, [
            'pay_status' => 1,
            'pay_images' => serialize($images),
            'pay_time' => date('Y-m-d H:i:s')
        ]);
    }

    public function detail($id)
    {
        $repairReconciliationObj = (new SsyRepairReconciliationOrderTable())->where('id', $id)->first()->toArray();
        $ids = unserialize($repairReconciliationObj['purchasein_ids']);
        //回货单明细
        $returnList = [];
        $processingMap = [];
        if(!empty($ids)){
            $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $ids)->orderBy('id', 'asc')->get()->toArray();
            $processingCodes = array_column($returnList, 'processing_code');
            if(!empty($processingCodes)){
                $processingList = (new SsyProcessingListTable())->whereIn('processing_code', $processingCodes)->groupBy(["processing_code", "factory_contract_no"])
                    ->get(["processing_code", "factory_contract_no"])->toArray();
                $processingMap = array_column($processingList, 'factory_contract_no', 'processing_code');
            }
        }
        foreach($returnList as &$item){
            $item['factory_contract_no'] = $processingMap[$item['processing_code']] ?? "";
        }
        $repairReconciliationObj['list'] = $returnList;
        //返修罚款
        $repairReconciliationObj['repair_list'] = [];
        $repairIds = unserialize($repairReconciliationObj['repair_ids']);
        if(!empty($repairIds)){
            $repairReconciliationObj['repair_list'] = (new SsyRepairAmountTable())->whereIn('id', $repairIds)->orderBy('id', 'asc')->get()->toArray();
        }
        //对账信息汇总
        $repairReconciliationObj['info'] = [
            [
                'purchasein_amount' => $repairReconciliationObj['purchasein_amount'],
                'repair_amount' => $repairReconciliationObj['repair_amount'],
                'pay_amount' => $repairReconciliationObj['pay_amount']
            ]
        ];
        //工厂银行信息
        $repairReconciliationObj['bank'] = (new SsyProcessingFactoryNameTable())->where('supplier_id', $repairReconciliationObj['supplier_id'])
            ->get(["company_head","bank_of_deposit","opening_bank_no","bank_account"])->toArray();
        return $repairReconciliationObj;
    }

    public function create($param)
    {
        $repairIds = array_map(function ($item){return (Int)$item;}, $param['repair_ids'] ?? []);
        $returnIds = array_map(function ($item){return (Int)$item;}, $param['return_ids'] ?? []);
        $exist = (new SsyRepairReconciliationOrderTable())->where('status', '<>', 3)->where('supplier_id', $param['supplier_id'])->where('recon_time', $param['date'])
            ->exists();
        if($exist){
            return ['code' => -1, 'msg' => '该工厂当前月份的采退/返修对账单已经存在了'];
        }
        $subject = array_column(config("scm.subject"), 'supplier_id', 'brand_code_s');
        if(!isset($subject[$param['brand_code']])){
            return ['code' => -1, 'msg' => '未知对账主体 请联系管理员！'];
        }
        $factoryObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $param['supplier_id'])->first();
        $renumber = "FXDZ".$param['supplier_id'].str_replace("-", "", $param['date']);
        $repairAmount = (new SsyRepairAmountTable())->whereIn('id', $repairIds)->sum("amount");
        $repairNum = (new SsyRepairAmountTable())->whereIn('id', $repairIds)->sum("num");
        $returnAmount = 0;
        $returnNum = 0;
        if(!empty($returnIds)){
            $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $returnIds)->get(['totalnum', 'pay_price'])->toArray();
            foreach ($returnList as $item){
                $returnNum += $item['totalnum'];
                $payPrice = round($item['totalnum'] * $item['pay_price'], 2);
                if($payPrice < 0){
                    return ['code' => -1, 'msg' => '回货金额不能小于0'];
                }
                $returnAmount += $payPrice;
            }
        }
        $data = [
            "supplier_id" => $param['supplier_id'],
            "renumber" => $renumber,
            "createtime" => date('Y-m-d H:i:s'),
            "recon_time" => $param['date'],
            "kaip_amount" => $returnAmount-$repairAmount,//开票金额
            "pay_amount" => $returnAmount-$repairAmount,//支付金额
            "factory_name" => $factoryObj->factory_name,
            "source_factory_groups_id" => $subject[$param['brand_code']],
            'adduser' => auth()->guard("api")->user()->name,
            "repair_ids" => !empty($repairIds) ? serialize($repairIds) : "",
            "repair_amount" => $repairAmount,
            "repair_num" => $repairNum,
            "purchasein_amount" => $returnAmount,
            "purchasein_ids" => empty($returnIds) ? "" : serialize($returnIds),
            "purchasein_num" => $returnNum,
        ];
        return (new SsyRepairReconciliationOrderTable())->createData($data);
    }
}
